<template>
  <div class="app-container">
    <div class="Search">
      <!--工具条-->
      <el-col :span="24" class="toolbar" style="padding-bottom: 0px;">
        <el-form :inline="true" :model="query">
          <el-form-item v-has="'PLATFROM_TENANT_QUERY'">
            <el-cascader ref="tenantTree" placeholder="所属租户" :props="tenantProps" :options="tenantOptions" @change="selectTenant" clearable collapse-tags filterable></el-cascader>
          </el-form-item>
          <el-form-item>
            <el-cascader ref="organTree" placeholder="所属组织" :props="props" :options="organOptions" @change="selectOrgan" clearable collapse-tags filterable></el-cascader>
          </el-form-item>
          <el-form-item>
            <el-select v-model="query.params.organType" placeholder="组织类型">
              <el-option v-for="item in query.typeOptions" :key="item.value" :label="item.label" :value="item.value" />
            </el-select>
          </el-form-item>
          <el-form-item>
            <el-input v-model="query.params.organTypeName" placeholder="组织类型名称" />
          </el-form-item>
          <el-form-item>
            <el-button type="primary" icon="el-icon-search" size="mini" @click="fetchData">查询</el-button>
          </el-form-item>
          <el-form-item>
            <el-button type="success" icon="el-icon-plus" size="mini" @click="handleAdd">新增</el-button>
          </el-form-item>
        </el-form>
      </el-col>
    </div>
    <div class="block">
      <el-table v-loading="listLoading" :data="list" element-loading-text="Loading" border fit highlight-current-row>
        <el-table-column align="center" label="序号" width="95">
          <template slot-scope="scope">
            {{ scope.$index }}
          </template>
        </el-table-column>
        <el-table-column label="所属组织" width="110">
          <template slot-scope="scope">
            {{ scope.row.organName }}
          </template>
        </el-table-column>
        <el-table-column label="组织类型" width="110" prop="type" :formatter="typeFormat">
        </el-table-column>
        <el-table-column label="组织类型名称" width="110">
          <template slot-scope="scope">
            {{ scope.row.organTypeName }}
          </template>
        </el-table-column>
        <el-table-column label="备注" width="110">
          <template slot-scope="scope">
            {{ scope.row.remark }}
          </template>
        </el-table-column>
        <el-table-column fixed="right" align="center" prop="created_at" label="操作">
          <template slot-scope="scope">
            <el-link type="warning" style="cursor: pointer;" icon="el-icon-edit" @click="handleEdit(scope.$index, scope.row)">
              {{ scope.row.isSet?'保存':"修改" }}
            </el-link>
            <el-divider direction="vertical"></el-divider>
            <el-link v-if="!scope.row.isSet" type="danger" class="el-icon-delete" style="cursor: pointer;" @click="handleDelete(scope.$index, scope.row)">
              删除
            </el-link>
            <el-divider direction="vertical"></el-divider>
            <el-link type="primary" style="cursor: pointer;" @click="handleAuthoritiesAssignedEdit(scope.$index, scope.row)">
              授权功能权限
            </el-link>
            <el-divider direction="vertical"></el-divider>
            <el-link type="primary" style="cursor: pointer;" @click="handleOrganSharingEdit(scope.$index, scope.row)">
              授权组织类型
            </el-link>
          </template>
        </el-table-column>
      </el-table>
    </div>
    <div class="block">
      <el-pagination :current-page="currentPage" :page-sizes="[10, 20, 30, 40]" :page-size="pageSize" layout="total, sizes, prev, pager, next, jumper" :total="total" @size-change="handleSizeChange" @current-change="handleCurrentChange" />
    </div>
    <div class="block">
      <!--弹框-->
      <el-dialog :title="titleMap[dialogStatus]" :visible.sync="dialogFormVisible">
        <el-form :model="form">
          <el-form-item v-if="addForVisible" label="编号">
            <el-input v-model="form.id" placeholder="编号" auto-complete="off" :disabled="true" />
          </el-form-item>
          <el-form-item v-has="'PLATFROM_TENANT_QUERY'" label="所属租户" placeholder="所属租户" required>
            <el-cascader v-model="form.tenantId" ref="tenantTreeForm" placeholder="所属租户" :props="tenantProps" :options="tenantOptions" @change="chooseTenantForm" style="width:100%" clearable collapse-tags filterable></el-cascader>
          </el-form-item>
          <el-form-item label="所属组织">
            <el-cascader v-model="form.organId" ref="organTreeForm" placeholder="所属组织" :props="props" :options="organFormOptions" @change="chooseOrganForm" style="width:100%" collapse-tags filterable></el-cascader>
          </el-form-item>
          <el-form-item label="组织类型">
            <el-select v-model="form.organType" placeholder="组织类型" style="width:100%">
              <el-option v-for="item in query.typeOptions" :key="item.value" :label="item.label" :value="item.value" />
            </el-select>
          </el-form-item>
          <el-form-item label="组织类型名称">
            <el-input v-model="form.organTypeName" placeholder="组织类型名称" auto-complete="off" />
          </el-form-item>
          <el-form-item label="备注">
            <el-input v-model="form.remark" placeholder="备注" auto-complete="off" />
          </el-form-item>
        </el-form>
        <div slot="footer" class="dialog-footer">
          <el-button @click="dialogFormVisible = false">取 消</el-button>
          <el-button type="primary" @click="handleEditSave">确 定</el-button>
        </div>
      </el-dialog>
    </div>
    <div class="block">
      <!--弹框-->
      <el-dialog :title="titleMap[dialogStatus]" :visible.sync="dialogFormForAssignAuthorityVisible">
        <el-form :inline="true" :model="organType">
          <el-form-item>
            <el-input v-if="false" v-model="organType.id" placeholder="待分配权限组织" hidden />
          </el-form-item>
          <el-form-item v-has="'PLATFROM_TENANT_QUERY'" label="所属租户" placeholder="所属租户" required>
            <el-cascader v-model="form.tenantId" ref="tenantTreeForm" placeholder="所属租户" :props="tenantProps" :options="tenantOptions" @change="chooseTenantForm" style="width:100%" clearable collapse-tags filterable></el-cascader>
          </el-form-item>
          <el-form-item label="所属组织">
            <el-cascader v-model="form.organId" ref="organTreeForm" placeholder="所属组织" :props="props" :options="organFormOptions" @change="chooseOrganForm" style="width:100%" collapse-tags filterable></el-cascader>
          </el-form-item>
        </el-form>
        <el-tree ref="authorityTree" :data="authorityList" :default-expand-all="true" :props="defaultProps" :check-strictly="false" show-checkbox node-key="id" highlight-current @current-change="currentChange" @check-change="checkChange" @check="authorityTreeCheck" />
        <div slot="footer" class="dialog-footer">
          <el-button @click="dialogFormForAssignAuthorityVisible = false">取 消</el-button>
          <el-button type="primary" @click="getAssignAuthoritiesAndSave">确 定</el-button>
        </div>
      </el-dialog>
    </div>
    <div class="block">
      <!--弹框-->
      <el-dialog :title="titleMap[dialogStatus]" :visible.sync="dialogFormForSharingVisible">
        <el-form :inline="true" :model="organType">
          <el-form-item v-has="'PLATFROM_TENANT_QUERY'" label="所属租户" placeholder="所属租户" style="width:100%" required>
            <el-cascader v-model="organType.tenantId" ref="tenantTreeForm" placeholder="所属租户" :props="tenantProps" :options="tenantOptions" @change="chooseTenantForSharing" clearable collapse-tags filterable></el-cascader>
          </el-form-item>
        </el-form>
        <el-tree ref="organSharingTree" :data="organFormOptions" :default-expand-all="false" :props="defaultOrganProps" :check-strictly="false" show-checkbox node-key="id" highlight-current @current-change="currentChange" @check-change="checkChange" @check="authorityTreeCheck" />
        <div slot="footer" class="dialog-footer">
          <el-button @click="dialogFormForSharingVisible = false">取 消</el-button>
          <el-button type="primary" @click="getOrganTypeSelectedAndSave">确 定</el-button>
        </div>
      </el-dialog>
    </div>
  </div>
</template>
<script>
import { getList, doDelete, doEdit, getAssignedList, getOrganTypePagination } from '@/api/organType'
import { queryOrganTypeOrganList, authorizing } from '@/api/organTypeOrgan'
import { querySubordinateOrgan } from '@/api/Organ'
import { getOrganTypeAuthoritiesAssignedOrNot, assignedAndModifyOrganTypeAuthorities, getOriginOrganAuthoritiesAndOrganTypeAssignedOrNot } from '@/api/organTypeAuthority'
import { getDictionaryGroup } from '@/api/dictionary'
import { getOrganId, getTenantId, getOrganPath, getCurrentLoginUserId, getSuperManagerId, handleBuildTreeDataStruct, getSelectedNodes, getSelectedNodesObject, getSystemErrorCode } from '@/api/utils'
import { getTenantList, getOrganList, getDictionary } from '@/utils/auth'
import localStorageUtil from '@/utils/localStorageUtil'


export default {
  data() {
    return {
      list: [],
      listLoading: true,
      total: 5,
      currentPage: 1,
      pageSize: 10,
      dialogFormVisible: false,
      addForVisible: false,
      dialogFormForAssignAuthorityVisible: false,
      dialogFormForSharingVisible: false,
      isClearable: true, // 可清空（可选）
      isAccordion: true, // 可收起（可选）
      valueId: {}, // 初始ID（可选）
      authorityList: [],
      organList: [],
      defaultProps: {
        children: 'children',
        label: 'name',
        url: 'url'
      },
      defaultOrganProps: {
        children: 'children',
        label: 'organName',
      },
      organType: {
        id: '',
        tenantId: '',
        organId: ''
      },
      title: '组织',
      props: { // 配置项（必选）
        value: 'id',
        label: 'organName',
        children: 'children',
        title: '组织',
        multiple: false,
        checkStrictly: true,
        emitPath: false
        // disabled:true
      },
      tenantProps: { // 配置项（必选）
        value: 'id',
        label: 'organName',
        children: 'children',
        title: '租户',
        multiple: false,
        checkStrictly: true,
        emitPath: false
        // disabled:true
      },
      organFormOptions: [],
      tenantOptions: [],
      organTreeProps: {
        children: 'children',
        label: 'organName',
        url: 'url'
      },
      title: '组织',
      optionData: [{ id: '1', parentId: '2', organName: '平台', children: [] }],
      form: {
        id: '',
        organId: '',
        tenantId: '',
        organType: '',
        organPath: '',
        organTypeName: '',
        isDeleted: '',
        createBy: '',
        updateBy: '',
        createDate: '',
        updateDate: '',
        remark: ''
      },
      // 新增or编辑弹框标题(根据点击的新增or编辑按钮显示不同的标题)
      // 新增or编辑弹框标题(根据点击的新增or编辑按钮显示不同的标题)
      titleMap: {
        add: '新增角色',
        edit: '编辑角色',
        assign: '指派权限',
        sharingOrganType: '共享组织类型'
      },
      // 新增和编辑弹框标题
      dialogStatus: '',
      query: {
        params: {
          id: '', // 主键
          organId: '', // 所属
          organType: '', // 组织类型
          organPath: '', // 所属组织路径
          organTypeName: '', // 组织类型名称
          isDeleted: '', // 已删
          createBy: '', // 生成者
          updateBy: '', // 更
          createDate: '', // 生成日期
          updateDate: '', // 更新日期
          remark: ''
        },
        authority: {
          id: '',
          tenantId: '',
          organId: '',
        },
        timeValue: '',
        typeOptions: [{
          value: '1',
          label: '黄金糕'
        }, {
          value: '2',
          label: '双皮奶'
        }],
        value: ''
      }
    }
  },
  created() {
    let that = this
    this.initOrganTree(() => {
      that.setOrganQueryType()
    }, getOrganPath())
    this.handleFiltTenant()
    this.initOrganFormTree()
    this.handleBuildTypeOptions()
    this.fetchData()
  },
  methods: {
    typeFormat(row, column) {

      let label = ''
      for (let i = 0; i < this.query.typeOptions.length; i++) {
        if ('' + row.organType === this.query.typeOptions[i].value) {
          return this.query.typeOptions[i].label
        }
      }
      return label
    },
    fetchData() {
      this.listLoading = true
      this.createOrganQuery()
      this.currentPage = this.currentPage || 1
      this.pageSize = this.pageSize || 10
      getOrganTypePagination(this.query.params,
        this.currentPage,
        this.pageSize).then(response => {
        const data = response.data
        if (!data.entities || typeof data.successful != 'undefined') {
          this.$message({
            type: 'info',
            message: data.description || getSystemErrorCode(data.status)
          })
        }
        this.total = data.totalCount
        this.pageSize = data.pageSize
        this.currentPage = data.currentPage
        this.list = data.entities
        this.listLoading = false
      })
    },
    createOrganQuery() {
      // 选中了租户
      let tenantSelected = this.$refs['tenantTree'] && this.$refs['tenantTree'].getCheckedNodes() || []
      let organSelected = this.$refs['organTree'] && this.$refs['organTree'].getCheckedNodes() || []
      let that = this
      this.query.params.organId = null
      if (tenantSelected.length && tenantSelected[0]) {
        this.query.params.tenantId = tenantSelected[0].data.id
        if (organSelected.length && organSelected[0]) {
          if (this.props.multiple) {
            this.query.params.organId = null
            this.query.params.organIds = []
            if (organSelected.length && organSelected[0]) {
              organSelected.forEach(function (element) {
                that.query.params.organIds.push(element.data.id)
              })
            }
          } else if (organSelected.length && organSelected[0]) {
            this.query.params.organPath = organSelected[0] && organSelected[0].data.organPath
          }
        }
      } else {
        this.query.params.tenantId = getTenantId()
        if (organSelected.length && organSelected[0]) {
          if (this.props.multiple) {
            this.query.params.organId = null
            this.query.params.organIds = []
            if (organSelected.length && organSelected[0]) {
              organSelected.forEach(function (element) {
                that.query.params.organIds.push(element.data.id)
              })
            }
          } else if (organSelected.length && organSelected[0]) {
            this.query.params.organPath = organSelected[0].data.organPath
          }
        }

      }
      this.query.params.organId = this.query.params.organId || getOrganId()
      this.query.params.organPath = this.query.params.organPath || getOrganPath()
    },

    handleSizeChange(val) {
      this.currentPage = 1
      this.pageSize = val
      this.fetchData()

    },
    handleCurrentChange(val) {
      this.currentPage = val
      this.fetchData()
    },
    // 新增
    handleAdd() {
      // 显示弹框
      this.dialogFormVisible = true
      // 新增弹框标题
      this.dialogStatus = 'add'
      this.form.id = ''
      this.form.organId = getOrganId()
      this.form.organType = ''
      this.form.organPath = getOrganPath()
      this.form.organTypeName = ''
      this.form.isDeleted = ''
      this.form.createBy = getCurrentLoginUserId()
      this.form.updateBy = getCurrentLoginUserId()
      this.form.createDate = ''
      this.form.updateDate = ''
      this.form.remark = ''
      this.addForVisible = false
    },
    // 编辑
    handleEdit(index, row) {
      console.log(index)
      console.log(row)
      debugger
      let that = this
      this.initOrganFormTree(function() {
        // 显示弹框
        that.dialogFormVisible = true
      })
      this.form.id = row.id
      this.form.organId = row.organId
      this.form.organType = '' + row.organType
      this.form.organPath = row.organPath
      this.form.organTypeName = row.organTypeName
      this.form.isDeleted = row.isDeleted
      this.form.createBy = row.createBy
      this.form.updateBy = row.updateBy
      this.form.tenantId = row.tenantId
      this.form.remark = row.remark


      this.addForVisible = true
      // 编辑弹框标题
      this.dialogStatus = 'edit'
    },
    handleDelete(index, row) {
      console.log(index)
      console.log(row)

      this.$confirm('此操作将永久删除该记录, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
        center: true
      }).then(() => {
        doDelete(row.id).then(response => {
          const data = response.data
          console.log(data)
          if (data.status === 1) {
            this.$message({
              type: 'success',
              message: '操作成功!'
            })
            this.fetchData()
          } else if (data.status === 403) {
            this.$message({
              type: 'warning',
              message: data.description
            })
          } else {
            this.$message({
              type: 'info',
              message: '操作失败!'
            })
          }
        })
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        })
      })
    },
    getAssignAuthoritiesAndSave() {
      //TODO 获取组织当前指派的权限, 包括组织类型所属权限

      this.$confirm('此操作将会更改所选组织的权限, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
        center: true
      }).then(() => {

        debugger
        const checkedList = this.$refs.authorityTree.getCheckedNodes()
        const halfCheckList = this.$refs.authorityTree.getHalfCheckedNodes()
        const batchModify = []
        const allChecked = []

        for (let i = 0; i < checkedList.length; i++) {
          allChecked.push(checkedList[i])
        }

        for (let i = 0; i < halfCheckList.length; i++) {
          allChecked.push(halfCheckList[i])
        }

        for (let i = 0; i < allChecked.length; i++) {
          const organAuthority = {}
          organAuthority['id'] = allChecked[i].organTypeAuthorityId ? allChecked[i].organTypeAuthorityId : ''
          organAuthority['authorityId'] = allChecked[i].id
          organAuthority['organTypeId'] = this.organType.id
          organAuthority['parentId'] = allChecked[i].parentId
          organAuthority['authName'] = allChecked[i].name
          organAuthority['isDeleted'] = false
          batchModify.push(organAuthority)

        }
        //指定、修改组织权限
        assignedAndModifyOrganTypeAuthorities(batchModify, this.organType.id, getOrganId()).then(response => {
          console.log(response)
          const data = response.data
          if (data.status < 200 && data.status >= 1) {
            this.$message({
              type: 'success',
              message: '操作成功!'
            })
            this.dialogFormForAssignAuthorityVisible = false
          } else if (data.status === 403) {
            this.$message({
              type: 'warning',
              message: data.description
            })
          } else {
            this.$message({
              type: 'info',
              message: '操作失败!'
            })
          }
        })


      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消操作'
        })
      })

    },
    checkChange() {
      console.log("tree checkChange")
    },
    currentChange() {
      console.log("tree currentChange")
    },
    fetchAuthorities(index, row) {

      this.listLoading = true
      this.authlistLoading = true
      getOriginOrganAuthoritiesAndOrganTypeAssignedOrNot({ tenantId: row.tenantId, organId: row.organId, organTypeId: row.id }).then(response => {
        const data = response.data
        if (data.successful) {
          const selectedNodes = this.getSelectedNodes(data.data)
          this.authorityList = handleBuildTreeDataStruct(data.data, 'id', 'parentId')
          this.listLoading = false

          // this.setCheckedNodes(selectedNodes);
          this.defaultSelectedNodes = selectedNodes
          this.$nextTick(function() {
            this.handleDefaultAuthoritySelected(selectedNodes)
          })
        } else {
          this.$message.error(data.description || getSystemErrorCode(data.status));
          this.listLoading = false

        }

      })
    },
    fetchOrgans(index, row) {

      this.listLoading = true
      let that = this
      this.initOrganTree(function() {
        that.checkedOrganTree(that)
      }, getOrganPath(), that)
      // querySubordinateOrgan({ organPath: getOrganPath() }).then(response => {
      //     console.log(response)
      //     const data = response.data
      //     debugger
      //     this.optionData = handleBuildTreeDataStruct(data, 'id', 'parentId')
      //     this.listLoading = false
      // })
    },
    handleDefaultAuthoritySelected(selectedNodes) {
      for (let i = 0; i < selectedNodes.length; i++) {
        this.$refs.authorityTree.setChecked(selectedNodes[i], true, false)
      }
    },
    authorityTreeCheck(data, statusObj) {
      console.log(data)
      console.log(statusObj)

      /*const checkedList = statusObj.checkedNodes
      let checkedNodesAppend = [];

      for(let i = 0; i < checkedList.length; i++ ){

        if(!checkedList[i].hasAuthority){//当前选中，但未持久化到系统中
            checkedNodesAppend.push(checkedList[i])
        }

      }
      for(let i = 0; i < checkedNodesAppend.length; i++ ){
          this.organ.assignedAuthorities.push(checkedNodesAppend[i])
      }
        
      if(data.hasAuthority){
          this.organ.deletedAuthorities.push(data)
      }else{
          this.organ.assignedAuthorities.push(data)
      } 

      //TODO 当前点击节点取消选中的情况
      if(data.children){
          this.organ.deletedAuthorities.push(data)
          for(let i = 0; i < data.children.length ; i ++){
              this.organ.deletedAuthorities.push(data.children[i])
          }
      }*/

      //操作点击后

    },
    handleAuthoritiesAssignedEdit(index, row) {
      this.dialogFormForAssignAuthorityVisible = true
      this.dialogStatus = 'assign'
      this.organType.id = row.id
      this.form.tenantId = row.tenantId
      this.form.organId = row.organId
      this.fetchAuthorities(index, row);
    },
    handleOrganSharingEdit(index, row) {

      this.dialogFormForSharingVisible = true
      this.dialogStatus = 'sharingOrganType'
      this.organType.id = row.id
      this.organType.tenantId = row.tenantId || getTenantId()
      this.fetchOrgans(index, row);
    },
    handleBuildTypeOptions() {
      getDictionaryGroup({ sys: 1, bigType: "OrganType", organPath:getOrganPath(), organId: getOrganId() }).then(response => {
        const data = response.data
        let typeOptions = [];
        for (let i = 0; i < data.length; i++) {

          let option = {}
          option['value'] = data[i].value
          option['label'] = data[i].desc
          typeOptions.push(option)
        }
        this.query.typeOptions = typeOptions
      })
    },
    translateOrganTypeLabelToVal() {
      let that = this
      this.query.typeOptions.forEach(function(item, index) {
        //item 就是当日按循环到的对象
        //index是循环的索引，从0开始
        if (item.label == that.form.organType) {
          that.form.organType = item.value
        }
      })
    },
    handleEditSave() {
      debugger
      this.listLoading = true

      this.translateOrganTypeLabelToVal()
      doEdit(this.form).then(response => {
        debugger
        console.log(response)
        const data = response.data
        if (data.status) {
          this.$message({
            type: 'success',
            message: '操作成功!'
          })
          this.fetchData()
        } else {
          this.$message({
            type: 'info',
            message: '操作失败!'
          })
        }
        this.listLoading = false
        this.dialogFormVisible = false
      })
    },
    handleReset() {
      this.$confirm('此操作将永久删除该记录, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
        center: true
      }).then(() => {
        this.$message({
          type: 'success',
          message: '删除成功!'
        })
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        })
      })
    },
    getSelectedNodes(dataList) {
      const selectedNodes = []
      const selectedKeys = {}
      for (let i = 0; i < dataList.length; i++) {
        if (dataList[i].hasAuthority) {
          selectedNodes.push(dataList[i].id)
          selectedKeys[dataList[i].id] = true
        }
      }

      return selectedNodes
    },
    handleFiltTenant() {
      let data = getOrganList()
      this.tenantOptions = data.filter(function(item, index) {
        return item.type == 0 || item.type == 1;
      })
    },
    initOrganTree(fn, filter, that) {
      debugger
      this.listLoading = true
      let data = getOrganList()
      if (filter) {
        data = data.filter(function(item, index) {
          return item.organPath.indexOf(filter) >= 0
        })
      }
      if (that && that.organFormOptions) {
        that.organFormOptions = handleBuildTreeDataStruct(data, 'id', 'parentId')
      } else {
        this.organOptions = handleBuildTreeDataStruct(data, 'id', 'parentId')
      }
      this.listLoading = false
      if (fn) {
        fn()
      }
    },
    initOrganFormTree(fn, filter) {
      this.initOrganTree(fn, filter, this)
    },
    setOrganQueryType() {
      this.organQueryModelChange(localStorageUtil.fetch("SYSTEM_SETTING_ORGAN_QUERY_MODEL"))
    },
    selectOrgan(nodes) {
      let nodesInfo = this.$refs['organTree'].getCheckedNodes()
      let that = this
      this.query.params.organPath = ''
      this.query.params.organIds = []
      if (this.props.multiple) {
        this.query.params.organIds = []
        if (nodesInfo.length) {
          nodesInfo.forEach(function(element) {
            that.query.params.organIds.push(element.data.id)
          })
        }
      } else if (nodesInfo.length) {
        this.query.params.organPath = nodesInfo[0].data.organPath
      }
    },
    selectTenant(nodes) {
      debugger
      let nodesInfo = this.$refs['tenantTree'].getCheckedNodes()
      let that = this
      this.query.params.tenantId = ''
      this.query.params.tenantIds = []
      if (this.props.multiple) {
        this.query.params.tenantIds = []
        if (nodesInfo.length) {
          nodesInfo.forEach(function(element) {
            that.query.params.tenantIds.push(element.data.id)
          })
        }
      } else if (nodesInfo.length) {
        this.query.params.tenantId = nodesInfo[0].data.id
        this.initOrganTree(function() {
          that.setOrganQueryType()
        }, nodesInfo[0].data.organPath)
      } else {
        this.initOrganTree(function() {
          that.setOrganQueryType()
        })
      }
    },
    chooseTenantForm(nodes, fn) {
      let nodesInfo = this.$refs['tenantTreeForm'].getCheckedNodes()
      this.form.tenantId = null
      let that = this
      if (nodesInfo.length) {
        this.form.tenantId = nodesInfo[0].data.id
        this.form.organPath = nodesInfo[0].data.organPath
        this.initOrganTree(fn, nodesInfo[0].data.organPath, that)
      }
    },
    chooseTenantForSharing(nodes) {
      let that = this
      this.chooseTenantForm(nodes, function() {
        that.checkedOrganTree(that)
      })
    },
    checkedOrganTree(that) {
      queryOrganTypeOrganList({ tenantId: that.organType.tenantId, id: that.organType.id }).then(response => {
        const data = response.data.data
        const selectedNodes = []
        for (let i = 0; i < data.length; i++) {
          selectedNodes.push(data[i].organId)
        }
        if (selectedNodes.length) {
          that.$nextTick(function() {
            that.handleDefaultSelected(selectedNodes)
          })
        }

      })
    },
    handleDefaultSelected(selectedNodes) {
      for (let i = 0; i < selectedNodes.length; i++) {
        this.$refs.organSharingTree.setChecked(selectedNodes[i], true, false)
      }
    },
    getOrganTypeSelectedAndSave() {
      //TODO 获取组织当前指派的权限, 包括组织类型所属权限
      this.$confirm('您正在给所选的组织授权组织类型, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
        center: true
      }).then(() => {

        debugger
        const checkedList = this.$refs.organSharingTree.getCheckedNodes()
        const halfCheckList = this.$refs.organSharingTree.getHalfCheckedNodes()
        const batchModify = []
        const allChecked = []

        for (let i = 0; i < checkedList.length; i++) {
          allChecked.push(checkedList[i])
        }

        for (let i = 0; i < halfCheckList.length; i++) {
          allChecked.push(halfCheckList[i])
        }

        for (let i = 0; i < allChecked.length; i++) {
          const organTypeOrgan = {}
          organTypeOrgan['organId'] = allChecked[i].id
          organTypeOrgan['organPath'] = allChecked[i].organPath
          organTypeOrgan['organTypeId'] = this.organType.id
          organTypeOrgan['tenantId'] = this.form.tenantId
          organTypeOrgan['isDeleted'] = false
          batchModify.push(organTypeOrgan)

        }
        //指定、修改组织权限
        authorizing(batchModify, this.form.tenantId, this.organType.id).then(response => {
          console.log(response)
          const data = response.data
          if (data.status < 200 && data.status >= 1) {
            this.$message({
              type: 'success',
              message: '操作成功!'
            })
            this.dialogFormForAssignAuthorityVisible = false
          } else if (data.status === 403) {
            this.$message({
              type: 'warning',
              message: data.description
            })
          } else {
            this.$message({
              type: 'info',
              message: '操作失败!'
            })
          }
        })


      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消操作'
        })
      })

    },
    chooseOrganForm(nodes) {
      let nodesInfo = this.$refs['organTreeForm'].getCheckedNodes()
      if (nodesInfo[0]) {
        this.form.organPath = nodesInfo[0].data.organPath
        this.form.organId = nodesInfo[0].data.id
        this.form.tenantId = nodesInfo[0].data.tenantId
      }
    },
    organQueryModelChange(organQueryModel) {
      if (organQueryModel == 'selected') {
        this.props.multiple = true
      } else if (organQueryModel == 'selfAndSub') {
        this.props.multiple = false
      }
    },
  }
}

</script>
